package com.kwum.baijiahao;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

/**
 * @Description: 
 * @Company: yimo
 * @author: Kwum
 * @date 2018年2月9日 下午3:02:46
 */

public class BaiJiaHaoDemo {
	
	private static final String cookie = "AIDUID=7C27ED5DAC511B2B16DF44BF99513D6B:FG=1; "
			+ "BIDUPSID=7C27ED5DAC511B2B16DF44BF99513D6B; "
			+ "PSTM=1518145325; "
			+ "PSINO=6; "
			+ "H_PS_PSSID=1449_21116_18559_17001_20930; "
			+ "BDORZ=B490B5EBF6F3CD402E515D22BCDA1598; "
			+ "FP_UID=5894a70a9b9b547788a7a7c556e88b3c; "
			+ "BDUSS=kw2TjJwUEczNFItbUIzeHlnVkJERkxzLTItME1vY1VpYkhHalljVmZBUE8wNlJhQVFBQUFBJCQAAAAAAAAAAAEAAABgMFBU0rvOss"
			+ "Tny661xNPjMDAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAM5GfVrORn1aZ; "
			+ "Hm_lvt_f2ee7f5c2284ca4c112e62165bc44c75=1518158111; "
			+ "Hm_lpvt_f2ee7f5c2284ca4c112e62165bc44c75=1518159558";
	
	private static final String filePath = "F:\\CloudMusic\\MV\\Tizzy T,Jony J - 变.mp4";

	public static void main(String[] args) throws IOException {
//		preuploadVideo(cookie);
		
		videoUpload(cookie, "cfed41847870708641c9ea7b6bc18ccb", filePath);
	}

	public static void preuploadVideo(String cookies) throws IOException {
		Document document = Jsoup.connect("http://baijiahao.baidu.com/builder/author/video/preuploadVideo")
				.userAgent("Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36")
				.header("Cookie", cookies)
				.ignoreContentType(true)
				.post();
		System.out.println(document.text());
	}
	
	public static String videoUpload(String cookies, String uploadKey, String filePath) throws IOException {
		String result = null;
		File file = new File(filePath);
		if (!file.exists() || !file.isFile()) {
			throw new FileNotFoundException();
		}

		URL urlObj = new URL("http://rsbjh.baidu.com/builder/author/video/uploadVideo");
		HttpURLConnection con = (HttpURLConnection) urlObj.openConnection();
		con.setRequestMethod("POST"); // 设置关键值,以Post方式提交表单，默认get方式
		con.setDoInput(true);
		con.setDoOutput(true);
		con.setUseCaches(false); // post方式不能使用缓存
		con.setReadTimeout(480000);// 设置请求超时时间 8分钟
		// 设置请求头信息
		con.setRequestProperty("Accept", "*/*");
		con.setRequestProperty("Accept-Encoding", "utf-8");
		con.setRequestProperty("Accept-Language", "zh-CN,zh;q=0.8");
		con.setRequestProperty("Connection", "Keep-Alive");
		con.setRequestProperty("Cookie", cookies);
		con.setRequestProperty("User-Agent",
				"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36");
		// 设置边界
		String BOUNDARY = "----" + System.currentTimeMillis();
		con.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
		// 请求正文信息
		// 第一部分：
		StringBuilder sb = new StringBuilder();
		sb.append("--" + BOUNDARY); // 必须多两道线
		sb.append("\r\n");
		sb.append("Content-Disposition: form-data; name=\"timestamp\"");
		sb.append("\r\n");
		sb.append("\r\n");
		sb.append(System.currentTimeMillis());
		sb.append("\r\n");
		sb.append("--" + BOUNDARY); // 必须多两道线
		sb.append("\r\n");
		sb.append("Content-Disposition: form-data; name=\"id\"");
		sb.append("\r\n");
		sb.append("\r\n");
		sb.append("WU_FILE_0");
		sb.append("\r\n");
		sb.append("--" + BOUNDARY); // 必须多两道线
		sb.append("\r\n");
		sb.append("Content-Disposition: form-data; name=\"name\"");
		sb.append("\r\n");
		sb.append("\r\n");
		sb.append(file.getName());
		sb.append("\r\n");
		sb.append("--" + BOUNDARY); // 必须多两道线
		sb.append("\r\n");
		sb.append("Content-Disposition: form-data; name=\"type\"");
		sb.append("\r\n");
		sb.append("\r\n");
		sb.append("video/mp4");
		sb.append("\r\n");
		sb.append("--" + BOUNDARY); // 必须多两道线
		sb.append("\r\n");
		sb.append("Content-Disposition: form-data; name=\"size\"");
		sb.append("\r\n");
		sb.append("\r\n");
		sb.append(file.length());
		sb.append("\r\n");
		sb.append("--" + BOUNDARY); // 必须多两道线
		sb.append("\r\n");
		sb.append("Content-Disposition: form-data; name=\"chunks\"");
		sb.append("\r\n");
		sb.append("\r\n");
		sb.append("1");
		sb.append("\r\n");
		sb.append("--" + BOUNDARY); // 必须多两道线
		sb.append("\r\n");
		sb.append("Content-Disposition: form-data; name=\"chunk\"");
		sb.append("\r\n");
		sb.append("\r\n");
		sb.append("0");
		sb.append("\r\n");
		sb.append("--" + BOUNDARY); // 必须多两道线
		sb.append("\r\n");
		sb.append("Content-Disposition: form-data; name=\"upload_key\"");
		sb.append("\r\n");
		sb.append("\r\n");
		sb.append(uploadKey);
		sb.append("\r\n");
		sb.append("--" + BOUNDARY); // 必须多两道线
		sb.append("\r\n");
		sb.append("Content-Disposition: form-data;name=\"file\";filename=\"" + file.getName() + "\"\r\n");
		sb.append("Content-Type:application/octet-stream\r\n\r\n");
		byte[] head = sb.toString().getBytes("utf-8");
		// 获得输出流
		OutputStream out = new DataOutputStream(con.getOutputStream());
		// 输出表头
		out.write(head);
		// 文件正文部分
		// 把文件已流文件的方式 推入到url中
		DataInputStream in = new DataInputStream(new FileInputStream(file));
		int bytes = 0;
		byte[] bufferOut = new byte[1024];
		while ((bytes = in.read(bufferOut)) != -1) {
			out.write(bufferOut, 0, bytes);
		}
		in.close();
		// 结尾部分
		byte[] foot = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("utf-8");// 定义最后数据分隔线
		out.write(foot);
		out.flush();
		out.close();
		StringBuffer buffer = new StringBuffer();
		BufferedReader reader = null;
		try {
			// 定义BufferedReader输入流来读取URL的响应
			reader = new BufferedReader(new InputStreamReader(con.getInputStream(), "utf-8"));
			String line = null;
			while ((line = reader.readLine()) != null) {
				buffer.append(line);
			}
			if (result == null) {
				result = buffer.toString();
			}
			// System.out.println(JSONObject.fromObject(result).toString());
		} catch (IOException e) {
			System.out.println("发送POST请求出现异常！" + e);
			e.printStackTrace();
			throw new IOException("数据读取异常");
		} finally {
			if (reader != null) {
				reader.close();
			}
		}

		// 请求返回json
		// {"code":0,"message":"success","reason":"success","expect_bytes":-1,"bytes":-1,"poster_uri":"","poster_url":"","crc32":4218209540,"url":""}
		System.out.println(result);
		return result;
	}
}
